package com.cheche.dn.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * Util - Json
 * Created by CheShun on 2014/5/1.
 */
public class JsonUtil {
    private static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper()
                .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)            //允许单引号
                .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)     //允许没有引号的字段名
                .configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true)   //允许ASCII值小于32的控制字符
                .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)       //忽略map中的null属性
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .setSerializationInclusion(JsonInclude.Include.NON_NULL);           //忽略bean中的null属性
    }

    public static ObjectMapper getMapper() {
        return mapper;
    }

    public static String toJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T getEntity(String jsonObj, Class<T> clazz) throws IOException {
        return mapper.readValue(jsonObj, clazz);
    }

    public static <T> List<T> getEntityList(String jsonArr, Class<T> clazz) throws IOException {
        if (Strings.isNullOrEmpty(jsonArr)) {
            return Collections.emptyList();
        }
        JsonNode node = mapper.readTree(jsonArr);
        List<T> ts = Lists.newArrayList();
        for (int i = 0; i < node.size(); i++) {
            ts.add(mapper.readValue(node.get(i).toString(), clazz));
        }
        return ts;
    }
}